import apis from '@/services/apis.ts'
import { useTencentConversationStore } from '@/stores/tencentConversationStore.ts'
import TencentCloudChat, { Conversation } from '@tencentcloud/chat'

export const useTencentCloudSearchStore = defineStore(
  'TencentCloudSearchStore',
  () => {
    const tencentConversationStore = useTencentConversationStore()
    const userList = ref<any[]>([])
    const groupList = ref<any[]>([])
    const conversationList = ref<any[]>([])

    const searchUsers = (userName?: string) => {
      const form = new FormData()
      form.append('pageIndex', '1')
      form.append('pageSize', '15')

      if (userName) {
        form.append('userName', userName)
      }

      apis.getUserPage(form).then((res) => {
        userList.value = res.DataList
      })
    }

    const searchGroups = (groupName?: string) => {
      const form = new FormData()
      form.append('pageIndex', '1')
      form.append('pageSize', '15')

      if (groupName) {
        form.append('groupName', groupName)
      }

      apis.getGroupPage(form).then((res) => {
        groupList.value = res.DataList
      })
    }

    const searchConvs = (toUserName?: string) => {
      conversationList.value = []
      if (toUserName) {
        conversationList.value = tencentConversationStore.conversationList.filter((item: Conversation) => {
          return item.type === TencentCloudChat.TYPES.CONV_GROUP
            ? item.conversationID.endsWith(toUserName)
            : item.userProfile?.nick.indexOf(toUserName) !== -1
        })
      }
    }

    const searchAll = (keyword: string) => {
      searchUsers(keyword)
      searchGroups(keyword)
      searchConvs(keyword)
    }

    return {
      searchUsers,
      userList,
      groupList,
      searchGroups,
      searchConvs,
      conversationList,
      searchAll
    }
  },
  {
    share: {
      enable: true,
      initialize: true
    }
  }
)
